package com.zhangye.test.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhangye.test.entity.EasyArResult;
import com.zhangye.test.mapper.AccountMapper;
import com.zhangye.test.mapper.AccountPayMapper;
import com.zhangye.test.mapper.AdminMapper;
import com.zhangye.test.mapper.AlipayOrderInfoMapper;
import com.zhangye.test.mapper.EasyArMapper;
import com.zhangye.test.model.AccountPay;
import com.zhangye.test.model.Admin;
import com.zhangye.test.model.AlipayOrderInfo;
import com.zhangye.test.model.EasyAr;
import com.zhangye.test.util.RSA;
import com.zhangye.test.util.StringUtils;
import com.zhangye.test.util.cloudUtils;


@Service
public class AliPayVerifyService {
	
	Logger logger = LoggerFactory.getLogger(AliPayVerifyService.class);

	@Autowired
	private AlipayOrderInfoMapper aliPayOrderInfoMapper;

	@Autowired
	private AccountPayMapper accountPayMapper;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private PayListService payListService;

	@Autowired
	private BusinessService businessService;

	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private EasyArMapper easyArMapper;

	
	/**
	 * 修改支付成功后操作
	 * 作者： 张叶
	 * 创建时间：2018年6月4日  下午5:53:04
	 */
	@Transactional
	public Map<String, String> verifyNew(Map<String, Object> param) throws ParseException{

		AlipayOrderInfo ap;
		AccountPay acp;
		Map<String,Object>  response = new HashMap<String,Object>();
		Map<String,Object>  alipay = new HashMap<String,Object>();
		Map<String,String>  result = new HashMap<String,String>();
		result.put("resultCode", "1");
		
		response = JSONObject.fromObject(param.get("result"));
		alipay = (Map<String, Object>) response.get("alipay_trade_app_pay_response");//签名原始字符串
		String sign = (String) response.get("sign");
		String resultStatus = (String) param.get("resultStatus");//结果码
		double total_amount = Double.parseDouble((String) alipay.get("total_amount"));
		String order = "";
		if (param.get("order") != null && !"".equals(param.get("order"))) {
			order = (String) param.get("order");
		}
		String res = "";
		
		//验证签名是否合法
		if (RSA.verify(alipay.toString(), sign)) {
			String where = " and outTradeNo = '" + alipay.get("out_trade_no") + "'";
			where += " and totalAmount = " + total_amount;
			List<AlipayOrderInfo> list = aliPayOrderInfoMapper.selectByWhere(where);
			if (list.size() == 1) {
				String subject = list.get(0).getSubject();
				result.put("outTradeNo", alipay.get("out_trade_no").toString());
				if (alipay.get("seller_id").equals("2088421943565793")) {
					if (alipay.get("app_id").equals("2016101702208037")) {
						//判断订单是否处理过
						String where3 = " and outTradeNo = '" + alipay.get("out_trade_no") + "'";
							where3 += " and deleteLogo = '0'";
						List<AccountPay> accountp = accountPayMapper.selectByWhere(where3);
						if (accountp.size() > 0) {
							result.put("resultCode", "0");
							logger.info("重复订单，订单号：" + alipay.get("out_trade_no"));
						} else {
							if (resultStatus.equals("9000")) {
								acp = new AccountPay();
								acp.setUserid(list.get(0).getUserid());
								acp.setInserttime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
								acp.setTotalamount(Double.valueOf(total_amount));
								acp.setBalance(Double.valueOf(total_amount));
								acp.setVariation("+"+total_amount);
								acp.setPayway("支付宝支付");
								acp.setOuttradeno(alipay.get("out_trade_no").toString());
								acp.setPhporder(order);
								acp.setPhpresult(res);
								acp.setDeletelogo(0);
								if (accountPayMapper.insert(acp) > 0) {
									//支付成功更新admin表
									int b = 0;
									Long aId = (long)list.get(0).getUserid();
									Admin admin = adminMapper.selectByPrimaryKey(aId);
									try{
										int counts = list.get(0).getTotalamount().intValue();
										admin.setCounts(admin.getCounts() + counts);
										b = adminMapper.updateByPrimaryKey(admin);
										updateCounts(aId);//更新管理员次数
										if (b == 1) {
											result.put("resultCode", "0");
										} else {
											logger.info("交易成功，更新业务表admin失败，订单号：" + alipay.get("out_trade_no"));
										}
									}catch (Exception e){
										
									}
								} else {
									logger.info("交易成功，插入account_pay表失败，订单号：" + alipay.get("out_trade_no"));
								}
							}
						}
					}
				}
			}
			//更新aliPay_orderInfo表
			ap = new AlipayOrderInfo();
			ap.setResultstatus(resultStatus);
			ap.setCode(alipay.get("code").toString());
			ap.setOuttradeno(alipay.get("out_trade_no").toString());
			ap.setUpdatetime(new Date());
			int i = aliPayOrderInfoMapper.updateByPrimaryKey(ap);
			if (i == 0) {
				logger.info("aliPay_orderInfo表更新失败，订单号：" + alipay.get("out_trade_no"));
			}
		} else {
			logger.info("签名验证失败，订单号：" + alipay.get("out_trade_no"));
		}
		return result;
	}


	/**
	 * 更新管理员次数
	 * 作者： 张叶
	 * 创建时间：2018年8月24日  上午9:55:48
	 */
	private void updateCounts(Long aId) {
		String where;
		where = " and admin_id = " + aId;
		List<EasyAr> lists = easyArMapper.selectByWhere(where);
		if(lists.size() > 0){
			for(EasyAr ea : lists){
				if(ea.getActive() == 0){
					ea.setActive(1);
					EasyArResult er;
					try {
						er = cloudUtils.updateCloud(ea.getTargetId(),ea.getActive().toString(),ea.getName());
						String status = er.getStatusCode();
						if(status.equals("0")){//修改成功，改库
							easyArMapper.updateByPrimaryKey(ea);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
}
